package com.xry.test1.controller;

import com.xry.test1.common.Result;

import com.xry.test1.model.UserRequest;
import com.xry.test1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 注册接口
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody UserRequest request) {
        try {
            userService.register(request.getUsername(), request.getPassword());
            return Result.success("注册成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody UserRequest request) {
        System.out.println("收到的请求: 用户名 = " + request.getUsername() + ", 密码 = " + request.getPassword());
        try {
            String token = userService.login(request.getUsername(), request.getPassword());

            return Result.success(token);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}
